package android.lollapalooza;

import service.LollaService;
import service.LollaServiceImpl;
import util.LollaException;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.widget.TabHost;
import android.widget.Toast;
import entities.Band;
import entities.Event;
import entities.Venue;

/**
 * Entry point for the Lollapalooza app. Launches on application start up.
 */
public class Lollapalooza extends TabActivity {

	private LollaService mService;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tablayout);
		mService = new LollaServiceImpl(getApplicationContext());
		Boolean isSynced = checkSync();
		if (!isSynced)
			runInitialSync();

		initializeTabs();
	}

	/**
	 * Reloads the Activity.
	 * 
	 * @param isDataSync
	 *            Indicates whether or not the Activity is being reloaded from a
	 *            data sync.
	 * @param isSyncSuccessful
	 *            Indicates whether or not the previous data sync was
	 *            successful.
	 */
	public void reload(Boolean isDataSync, Boolean isSyncSuccessful) {
		Intent intent = getIntent();
		overridePendingTransition(0, 0);
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		intent.putExtra("SYNC", isDataSync);
		intent.putExtra("SYNC_SUCCESSFUL", isSyncSuccessful);
		finish();
		overridePendingTransition(0, 0);
		startActivity(intent);
	}

	/**
	 * Checks if the calling Activity executed a data sync. Returns true if it
	 * did, false if not. Creates a Toast popup notifying whether the sync was
	 * successful or not.
	 * 
	 * @return True if a data sync was executed, false if not
	 */
	private Boolean checkSync() {
		Intent i = getIntent();
		Boolean isSync = i.getBooleanExtra("SYNC", false);
		if (isSync) {
			Boolean isSuccessful = i.getBooleanExtra("SYNC_SUCCESSFUL", false);
			if (isSuccessful)
				Toast.makeText(this, getString(R.string.sync_success),
						Toast.LENGTH_LONG).show();
			else
				Toast.makeText(this, getString(R.string.sync_fail),
						Toast.LENGTH_LONG).show();
		}
		return isSync;
	}

	/**
	 * Runs the data sync process. This kicks off a new thread.
	 */
	private void runInitialSync() {
		long recordCount = mService.countType(Band.class)
				+ mService.countType(Event.class)
				+ mService.countType(Venue.class);
		DataSyncThread syncThread = null;
		if (recordCount == 0) {
			syncThread = new DataSyncThread(this);
			syncThread.start();
		}
	}

	/**
	 * Configures and initializes the tab layout for this Activity.
	 */
	private void initializeTabs() {
		Resources res = getResources(); // Resource object to get Drawables
		TabHost tabHost = getTabHost(); // The activity TabHost
		TabHost.TabSpec spec; // Resusable TabSpec for each tab
		Intent intent; // Reusable Intent for each tab

		// Create an Intent to launch an Activity for the tab (to be reused)
		intent = new Intent().setClass(this, Artists.class);

		// Initialize a TabSpec for each tab and add it to the TabHost
		spec = tabHost.newTabSpec(getString(R.string.artists)).setIndicator(
				getString(R.string.artists),
				res.getDrawable(R.xml.ic_tab_artists)).setContent(intent);
		tabHost.addTab(spec);

		// Do the same for the other tabs
		intent = new Intent().setClass(this, Events.class);
		spec = tabHost.newTabSpec(getString(R.string.events)).setIndicator(
				getString(R.string.events),
				res.getDrawable(R.xml.ic_tab_artists)).setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, Venues.class);
		spec = tabHost.newTabSpec(getString(R.string.venues)).setIndicator(
				getString(R.string.venues),
				res.getDrawable(R.xml.ic_tab_artists)).setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, Updates.class);
		spec = tabHost.newTabSpec(getString(R.string.updates)).setIndicator(
				getString(R.string.updates),
				res.getDrawable(R.xml.ic_tab_artists)).setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, Updates.class);
		spec = tabHost.newTabSpec(getString(R.string.mylolla)).setIndicator(
				getString(R.string.mylolla),
				res.getDrawable(R.xml.ic_tab_artists)).setContent(intent);
		tabHost.addTab(spec);
	}

	/**
	 * Thread that executes the data sync process.
	 */
	private class DataSyncThread extends Thread {
		private LollaService service;
		private ProgressDialog progress;
		private Lollapalooza caller;

		public DataSyncThread(Lollapalooza caller) {
			service = new LollaServiceImpl(caller);
			progress = ProgressDialog.show(caller, caller
					.getString(R.string.loading_title), caller
					.getString(R.string.loading), true);
			this.caller = caller;
		}

		@Override
		public void run() {
			try {
				Log.i("Lollapalooza", "Beginning data sync process");
				service.saveAll();
				Log.i("Lollapalooza", "Data sync process complete");
				//Log.i("Lollapalooza", "Building and saving images to database");
				//service.buildAndSaveImages();
				//Log.i("Lollapalooza", "Image data process complete");
				caller.runOnUiThread(new Runnable() {
					public void run() {
						caller.reload(true, true);
					}
				});
			} catch (LollaException ex) {
				caller.runOnUiThread(new Runnable() {
					public void run() {
						caller.reload(true, false);
					}
				});
			} finally {
				progress.dismiss();
				TabHost tabHost = getTabHost();
				tabHost.setCurrentTab(0);
			}
		}
	}

}